<template>
  <div class="structure-tree">
    <header>
      <h2>设备类型</h2>
      <el-icon class="add" @click="deptEvent({ id: '0', deptName: '' }, 1)"
        ><ele-CirclePlus
      /></el-icon>
    </header>
    <el-input
      v-model="filterText"
      placeholder="可输入设备类型进行搜索"
      class="input"
    />
    <el-tree
      ref="treeRef"
      :data="treeData"
      :props="defaultProps"
      @node-click="nodeClick"
      default-expand-all
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      draggable
      :indent="6"
      @node-drop="nodeDragEnter"
    >
      <template #default="{ node, data }">
        <span
          class="custom-tree-node show-hide"
          :class="{ active: currentNode.id == data.id }"
        >
          <!-- <el-tooltip :content="node.label" placement="top" > -->
          <span v-if="node.label.length > 8" class="treeLabel">{{
            node.label
          }}</span>
          <!-- </el-tooltip> -->
          <span v-else>{{ node.label }}</span>
          <span class="operate">
            <a @click.stop="deptEvent(data, 1)">
              <el-icon><ele-Plus /></el-icon>
            </a>
            <a style="margin-left: 8px" @click.stop="deptEvent(data, 2)">
              <el-icon><ele-Edit /></el-icon>
            </a>
            <el-popconfirm
              width="150"
              confirm-button-text="删除"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="#FC770A"
              title="确定删除？"
              @confirm="deleteEvent(data)"
            >
              <template #reference>
                <a style="margin-left: 8px" @click.stop="">
                  <el-icon><ele-Delete /></el-icon>
                </a>
              </template>
            </el-popconfirm>
          </span>
        </span>
      </template>
    </el-tree>
    <DictionariesTreeDialog
      :dialogVisible="dialogVisible"
      :dialogForm="dialogForm"
      :dialogDetail="dialogDetail"
      @cancel="cancel"
      @submit="submit"
    >
    </DictionariesTreeDialog>
  </div>
</template>

<script lang="ts" setup>
import { InfoFilled } from '@element-plus/icons-vue'
import { ElMessage, ElTree } from 'element-plus'
import { ref, watch, onMounted, defineAsyncComponent } from 'vue'
import emitter from '/@/utils/mitt'
import { Session } from '/@/utils/storage'
import {
  dictionaryList,
  deleteDictionary,
  updateSort
} from '/@/api/setting/index'
import {
  updateDictionaryIdAndSortApi,
  updateParentIdAndSortApi
} from '/@/api/publicApi'

const DictionariesTreeDialog = defineAsyncComponent(
  () => import('./DictionariesTreeDialog.vue')
)

//输入框
const filterText = ref('')

const treeRef = ref<InstanceType<typeof ElTree>>()

const dialogVisible = ref<boolean>(false) //弹窗是否出现
const dialogForm = {
  width: '25%',
  title: ''
}
const dialogDetail = ref<any>({})

interface Tree {
  deptName: string
  parentName: string
  id: string
  parentId: string
  children?: Tree[]
}
const defaultProps = {
  children: 'children',
  label: 'configValue'
}

let treeData = ref<Tree[]>([] as Tree[])
let currentNode = ref()
const configType = 'device_type'

// 递归，求树第一个子项，用于第一次进页面默认选中
const getDepth = (obj: any) => {
  let cur = {}
  if (obj[0].children && obj[0].children.length) {
    cur = getDepth(obj[0].children)
  } else {
    cur = obj[0]
  }
  return cur
}

const getTreeList = async (val: any) => {
  const params = { configType: configType }
  let res = await dictionaryList(params)
  if (res.code == 0) {
    treeData.value = res.data
    if (treeData.value.length) {
      if (val == '') {
        currentNode.value = getDepth(treeData.value)
        emitter.emit('deviceCurrentNode' as any, currentNode.value)
      } else {
        treeItem(treeData.value, val)
      }
    }
  }
}
onMounted(() => {
  getTreeList('')
})

//树条目点击
const nodeClick = (data: Tree) => {
  currentNode.value = data
  emitter.emit('deviceCurrentNode' as any, currentNode.value)
}

//弹框取消点击
const cancel = () => {
  dialogVisible.value = !dialogVisible.value
}
//弹框确定点击
const submit = (val: any) => {
  dialogVisible.value = !dialogVisible.value
  getTreeList(val)
}

const treeItem = (val: any, name: any) => {
  for (let index = 0; index < val.length; index++) {
    const element = val[index]
    if (element.configValue == name) {
      currentNode.value = element
      emitter.emit('deviceCurrentNode' as any, currentNode.value)
      return
    } else {
      if (element.children) {
        treeItem(element.children, name)
      }
    }
  }
}

const deleteEvent = async (node: Tree) => {
  let res = await deleteDictionary(node.id)
  if (res.code == 0) {
    ElMessage.success('删除成功！')
    getTreeList('')
  }
}

const shebei = Session.get('shebei')
//拖拽移动进入摸节点
const nodeDragEnter = (node1: any, node2: any, wz: any, event: any) => {
  let params = {
    id: node1.data.id,
    parentId: node2.data.id,
    sort: 1,
    companyId: shebei.companyId
  }
  updateDictionaryIdAndSortApi(params).then((res) => {
    if (res.code == 0) {
      ElMessage.success('移动成功')
      getTreeList('')
    }
  })
}

/**
 * @param data 新增或者编辑数据
 * @param t 类型,1新增,2编辑
 */
const deptEvent = (data: any, t: number) => {
  if (t === 1) {
    dialogForm.title = '新增'
    dialogDetail.value = { configType: configType, parentId: data.id }
  } else {
    dialogForm.title = '编辑'
    dialogDetail.value = data
  }
  dialogVisible.value = !dialogVisible.value
}

//搜索过滤
const filterNode = (value: any, data: any) => {
  if (!value) return true
  return data.configValue.includes(value)
}

//监听输入框搜索事件
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const ellipsis = (value: string, len: number) => {
  if (!value) return ''
  if (value.length > len) {
    return value.slice(0, len) + '...'
  }
  return value
}
</script>

<style scoped lang="scss">
.structure-tree {
  header {
    display: flex;
    // align-items: center;
    justify-content: space-between;
    height: 40px;

    h2 {
      font-size: var(--next-font-size16);
    }

    .add {
      font-size: var(--next-font-size18);
      color: var(--el-color-primary);
      margin: 3px 8px 0 0;
      cursor: pointer;
    }
  }

  .input {
    width: 90%;
    margin-bottom: 10px;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: var(--el-font-size-base);
  padding-right: 8px;
  .treeLabel {
    width: 160px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.custom-tree-node:hover {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: var(--el-font-size-base);
  padding-right: 8px;
  pointer-events: auto;

  .treeLabel {
    width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.show-hide :nth-child(2) {
  display: none;
}

.show-hide:hover :nth-child(2) {
  display: inline-block !important;
}

.operate {
  a {
    color: var(--el-color-primary);
  }
}

.active {
  color: var(--el-color-primary);
}
</style>
